import tools from '@/utils/tools'

type MethodType = 'GET' | 'OPTIONS' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
interface HttpResponse<T = any> {
  msg: T
  code: number
}
class Request {
  constructor(config) {
    uni.addInterceptor('request', {
      //请求触发前的回调函数
      invoke(args) {
        args.timeout = config.TIME_OUT
        args.url = config.BASE_URL + args.url
        args.header = {
          token: tools.getStorage('token') ?? ''
			// token: 'bdeaacf85c7a0e0e6f3385e7f870ff0a'
        }
      },
      //请求成功的回调函数
      success(res) {
        // console.log('interceptor-success', res)
      },
      //拦截失败回调函数
      fail(err) {
        console.log('interceptor-fail', err)
      }
    })
  }
  request<T>(url: string, method: MethodType, data?: any, header?: object): Promise<HttpResponse<T>> {
    return new Promise((resolve, reject) => {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      uni.request({
        url,
        method: method ?? 'GET',
        data,
        header,
        success(res: { data }) {
          // if (res.data.code == 2) return tools.navTo('/pagesA/group/lack?title=' + res.data.msg, 4)
            if (res.data.code == 4) return tools.navTo('/pages/mine/login')
          resolve(res.data as HttpResponse<T>)
        },
        fail(err) {
          reject(err)
        },
        complete: () => {
          // 关闭正在加载的图标
          uni.hideLoading()
        }
      })
    })
  }
  get<T>(url: string, params?: any): Promise<HttpResponse<T>> {
    const query = params
      ? Object.entries(params)
          .map(([k, v]) => `${k}=${v}`)
          .join('&')
      : ''
    const fullUrl = query ? `${url}?${query}` : url
    return this.request<T>(fullUrl, 'GET')
  }
  post<T>(url: string, data?: any): Promise<HttpResponse<T>> {
    return this.request<T>(url, 'POST', data)
  }
  put<T>(url: string, data?: any): Promise<HttpResponse<T>> {
    return this.request<T>(url, 'PUT', data)
  }
  delete<T>(url: string, data?: any): Promise<HttpResponse<T>> {
    return this.request<T>(url, 'DELETE', data)
  }
}
export default Request
